package com.ht.module.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.constant.AppletConstants;
import com.ht.constant.BusConstant;
import com.ht.constant.RedisConstants;
import com.ht.module.sys.entity.SysWxUser;
import com.ht.module.sys.mapper.SysWxUserMapper;
import com.ht.util.JsonResult;
import com.ht.util.JwtUtils;
import com.ht.util.RedisUtil;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @ProjectName: ht
 * @ClassName: LoginController
 * @Author: hejialun
 * @Description: 登录相关接口
 * @Date: 2021/5/18 23:08
 */
@RestController
@RequestMapping("/sys-login")
@Api(tags = "登录相关接口 ")
public class LoginController {
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private SysWxUserMapper sysWxUserMapper;

    @Value("${wxMini.appId}")
    public String appId;
    @Value("${wxMini.secret}")
    public String secret;
    //token过期时间
    @Value("${jwt.expireTime}")
    public long EXPIRE_TIME;

    @ApiOperation("微信登录")
    @RequestMapping(value = "/wxLogin",method = RequestMethod.POST)
    @Transactional
    public JsonResult wxLogin(@RequestBody @Valid SysWxUser en){
        if(StringUtil.isEmpty(en.getCode())){
            return JsonResult.error("code不能为空");
        }
        //微信接口服务,通过调用微信接口服务中jscode2session接口获取到openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + en.getCode() + "&grant_type=authorization_code";
        String str = com.bowei.officialwebsite.utils.WeChatUtil.httpRequest(url, "GET", null);
        JSONObject jsonObject= JSONObject.parseObject(str);
        //设置openID
        en.setOpenId(jsonObject.getString(AppletConstants.openId));
        en.setUnionId(jsonObject.getString(AppletConstants.unionId));
        //更新用户
        int i = sysWxUserMapper.update(
                en,
                new QueryWrapper<SysWxUser>()
                        .eq("open_id", en.getOpenId())
        );
        if(i==0){
            en.setCreateDate(LocalDateTime.now());
            //插入一个用户
            sysWxUserMapper.insert(en);
        }else{
            //查询出用户
            SysWxUser wxUser = sysWxUserMapper.selectOne(new QueryWrapper<SysWxUser>().eq("open_id", en.getOpenId()));
            en.setId(wxUser.getId());
        }
        HashMap<String, Object> jwtmap = new HashMap<>();
        jwtmap.put("id",en.getId());
        jwtmap.put("nickName",en.getNickName());
        //生成token
        String sign = JwtUtils.sign(jwtmap);
        //将token也加进去  先写个假的
        jsonObject.put("token",sign);

        //将用户信息存到redis
        redisUtil.set(RedisConstants.USER_INFOS_PREFIX+sign,jwtmap,EXPIRE_TIME);

        return JsonResult.success(jsonObject);
    }



    /*
     * @param randomStr:随机字符串
     * @Author hejialun
     * @Description: TODO(创建验证码)
     * @date 2021/5/25 9:55
     * @returns com.ht.util.JsonResult
     */
    @GetMapping(value = "/getCode")
    public JsonResult getCode(String randomStr) throws Exception {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = captcha.text();
        // 保存
        redisUtil.set(RedisConstants.VERIFICATION_CODE_PREFIX+randomStr,result,BusConstant.VERIFICATION_CODE_OVERDUE_TIME);
        return JsonResult.success(captcha.toBase64());

    }
}